package cc.yugu.yhdw.webserver.web.controller.security;

import cc.yugu.yhdw.common.annotation.NotLogin;
import cc.yugu.yhdw.common.annotation.ViewModel;
import cc.yugu.yhdw.common.constant.ConstEnum;
import cc.yugu.yhdw.common.constant.Constant;
import cc.yugu.yhdw.common.domain.basic.*;
import cc.yugu.yhdw.common.domain.hdw.*;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.utils.AuthImgUtils;
import cc.yugu.yhdw.common.utils.CodecUtils;
import cc.yugu.yhdw.common.utils.IdUtils;
import cc.yugu.yhdw.common.utils.YhdwUtils;
import cc.yugu.yhdw.webserver.constant.AppConstEnum;
import cc.yugu.yhdw.webserver.constant.AppConstant;
import cc.yugu.yhdw.webserver.entity.SessionUser;
import cc.yugu.yhdw.webserver.service.basic.*;
import cc.yugu.yhdw.webserver.service.hdw.*;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

import cc.yugu.yhdw.webserver.web.controller.security.SecurityController;
/**
 * 展示首页信息
 *
 * @Date:Created in 2018/8/1 16:02
 * @Author:
 * @Modified By: zxj 2018/8/1 16:02
 */
@Controller
@RequestMapping(value = "/security/main")
public class MainController extends SecurityController {

    final static Logger log = LogManager.getLogger(MainController.class);

    @Autowired
    AgentService agentService;
    @Autowired
    RoleService roleService;
    @Autowired
    ReportService reportService;
    @Autowired
    ItemOrderService itemOrderService;
    @Autowired
    PassportService passportService;
    @Autowired
    BatteryService batteryService;
    @Autowired
    AgencyService agencyService;
    @Autowired
    PlatformService platformService;
    @Autowired
    SupplierService supplierService;
    // 新增：
    @Autowired
    AgentInOutMoneyService agentInOutMoneyService;
    @Autowired
    AgencyInOutMoneyService agencyInOutMoneyService;
    @Autowired
    PlatformInOutMoneyService platformInOutMoneyService;

    /**
     * 跳转
     * @Param [model, step]
     * @Return void
     * @Author zxj 2018/8/1
     */
    @NotLogin
    @RequestMapping(value = "jump.htm")
    public void jump(Model model, String step) {
        model.addAttribute("step", step);
    }
    /**
     * 登陆（get）
     * @Param []
     * @Return void
     * @Author zxj 2018/8/1
     */
    @NotLogin
    @RequestMapping(value = "login.htm", method = RequestMethod.GET)
    public void login() {
    }
    /**
     * 验证图片
     * @Param [request, response]
     * @Return void
     * @Author zxj 2018/8/1
     */
    @NotLogin
    @RequestMapping(value = "auth_img.htm")
    public void authImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        AuthImgUtils.AuthImg authImg = AuthImgUtils.getAuthImg();
        HttpSession session = request.getSession(true);
        session.setAttribute(Constant.SESSION_AUTH_CODE, authImg.authCode);
        response.getOutputStream().write(authImg.buf);
    }
    /**
     * 预览（首页广告或者通知）
     * @Param [Path, model, httpSession]
     * @Return java.lang.String
     * @Author zxj 2018/8/1
     */
    @ViewModel(ViewModel.INNER_PAGE)
    @RequestMapping("preview.htm")
    public String preView(String Path, Model model, HttpSession httpSession) {
//        SessionUser sessionUser = getSessionUser(httpSession);
//        String videoSuffix = agentConfigService.find(sessionUser.getAgentId(), AppConstEnum.AgentConfigKey.VIDEO_SUFFIX.getValue()).getConfigValue();
//        String suffix = YhdwUtils.getFileSuffix(Path);
//        model.addAttribute("path", Path);
//        if(videoSuffix.indexOf(suffix) != -1) {
//            //视频
//            return "/security/main/video_preview";
//        }else {
//            //图片
//            return "/security/main/image_preview";
//        }
        return null;
    }
    /**
     * 登陆请求（post）
     * @Param [username, password, authCode, session]
     * @Return cc.yugu.yhdw.common.entity.json.ExtResult
     * @Author zxj 2018/8/1
     */
    @NotLogin
    @RequestMapping(value = "login.htm", method = RequestMethod.POST)
    @ResponseBody
    @ViewModel(ViewModel.JSON)
    public ExtResult login(String username, String password, String authCode, HttpSession session) {
        String storedAuthCode = (String) session.getAttribute(Constant.SESSION_AUTH_CODE);
        if (StringUtils.isEmpty(storedAuthCode) || !storedAuthCode.equalsIgnoreCase(authCode)) {
            return ExtResult.failResult("验证码错误");
        }
        // 根据用户名和密码获取用户信息
        User user = userService.findByLoginInfo(username, password);
        if (user == null) {
            return ExtResult.failResult("用户名或密码错误");
        }
        if (!ConstEnum.Flag.TRUE.getValue().equals(user.getActiveFlag())) {
            return ExtResult.failResult("用户未启用");
        }
        userService.updateLoginTime(user.getId());
        SessionUser sessionUser = new SessionUser();
        sessionUser.setId(user.getId());
        sessionUser.setUsername(user.getUsername());
        sessionUser.setRealName(user.getRealName());
        sessionUser.setPortrait(user.getPortrait());
        sessionUser.setSupplierId(user.getSupplierId() == null ? 0 : user.getSupplierId());
        sessionUser.setAgentId(user.getAgentId() == null ? 0 : user.getAgentId());
        sessionUser.setRootAgentId(user.getAgentId() == null ? 0 : user.getAgentId());
        sessionUser.setAgencyId(user.getAgencyId() == null ? 0 : user.getAgencyId());
        sessionUser.setType(user.getType());
        sessionUser.setDeptName(user.getDeptName());
        if (user.getType() == User.Type.PLATFORM.getValue()) {
            Platform platform = platformService.find();
            sessionUser.setBalance((double) platform.getBalance() / 100);
        } else if (user.getType() == User.Type.AGENCY.getValue()) {
            Agency agency = agencyService.find(user.getAgencyId());
            sessionUser.setBalance((double) agency.getBalance() / 100);
            sessionUser.setTel(agency.getTel());
            sessionUser.setMemo(agency.getMemo());
        } else if (user.getType() == User.Type.AGENT.getValue()) {
            Agent agent = agentService.find(user.getAgentId());
            sessionUser.setBalance((double) agent.getBalance() / 100);
            sessionUser.setTel(agent.getTel());
            sessionUser.setMemo(agent.getMemo());
        } else if (user.getType() == User.Type.SUPPLIER.getValue()) {
            Supplier supplier = supplierService.find(user.getSupplierId());
            sessionUser.setBalance((double) supplier.getBalance() / 100);
            sessionUser.setTel(supplier.getTel());
            sessionUser.setMemo("");
        } else {
            return ExtResult.failResult("用户类别不存在");
        }
        sessionUser.setAdmin(ConstEnum.Flag.TRUE.getValue().equals(user.getAdminFlag()));
        agentService.updateAgentData(sessionUser);
        // 获取客户的角色
        if (user.getRoleId() != null) {
            Role role = roleService.find(user.getRoleId());
            if (role != null) {
                sessionUser.setRoleName(role.getRoleName());
                sessionUser.setOperCodeSet(roleService.loadOperCode(user.getRoleId()));
            }
        }

        session.setAttribute(Constant.SESSION_KEY_USER, sessionUser);
        session.setAttribute("USER_TYPE_PLATFORM", User.Type.PLATFORM);
        session.setAttribute("USER_TYPE_AGENT", User.Type.AGENT);
        session.setAttribute("USER_TYPE_AGENCY", User.Type.AGENCY);
        session.setAttribute("USER_TYPE_SUPPLIER", User.Type.SUPPLIER);
        return ExtResult.successResult();
    }

    @NotLogin
    @RequestMapping(value = "logout.htm")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        if (session != null) {
            session.removeAttribute(Constant.SESSION_KEY_USER);
            session.invalidate();
        }
        response.sendRedirect(request.getContextPath() + "/security/main/login.htm");
    }
    /**
    * 不同用户登录时的数据显示不同；（新增：处理不同用户登录时的换电金额显示不同问题）
    * 
    * @Param: [httpSession, model]
    * @Return: java.lang.String
    * @Author By: zjn 2018/7/18  16:18
    */ 
    @RequestMapping(value = "index.htm")
    public String index(HttpSession httpSession, Model model) {
        model.addAttribute(MENU_CODE_NAME, AppConstEnum.Menu.MENU_00.getValue());
        SessionUser sessionUser = getSessionUser(httpSession);
        if (sessionUser.getType() == User.Type.SUPPLIER.getValue()) {
            return "redirect:/security/hdw/supplier/index.htm";
        }
        Integer agentId = sessionUser.getAgentId();
        Integer agencyId = sessionUser.getAgencyId();
        Calendar calendar = Calendar.getInstance();
        String statsDate = calendar.get(Calendar.YEAR) + "-" + String.format("%2s", String.valueOf(calendar.get(Calendar.MONTH) + 1)).replaceAll(" ", "0") + "-" + String.format("%2s", String.valueOf(calendar.get(Calendar.DAY_OF_MONTH))).replaceAll(" ", "0");
        // 统计代理商： 截取时间、总金额 换电收入(运营商 or 代理商)、订单数
        //变量：总金额
        Double exchangePrice=0.0;
        Map<String, Object> exchangeMap = null;

        Integer totalOrderNumber = null;
        Double itemPrice = 0.0;
        Integer itemtotal = 0;
        Integer totalFaultBattery = 0;
        Integer totalAbnormalBattery = 0;
        // 如果是代理商登录
        if(sessionUser.getType() == User.Type.AGENCY.getValue()){

            // 查询代理商日报表
            exchangeMap = reportService.findToDayStats(statsDate, agentId, agencyId);
            // 从代理商日报表获取所分 换电金额数
            exchangePrice = exchangeMap != null && exchangeMap.get("money") != null ? Double.parseDouble(exchangeMap.get("money").toString()) / 100 : 0.0;

            totalOrderNumber = exchangeMap != null && exchangeMap.get("count") != null ? Integer.parseInt(exchangeMap.get("count").toString()) : 0 ;

            // new 权限设置（运营商和代理商可以查看故障电池）
            totalFaultBattery = batteryService.findFaults(null, sessionUser.getAgencyId());
            // new 权限设置（运营商和代理商可以查看异常电池）--zxj-20180821
            totalAbnormalBattery = batteryService.findAbnormal(null, sessionUser.getAgencyId());
        }
        // 如果是运营商登录
        if (sessionUser.getType() == User.Type.AGENT.getValue()){

//            sessionUser.setTel(agent.getTel());
//            sessionUser.setMemo(agent.getMemo());
            // 查询运营商日报表
            exchangeMap = reportService.findAgentToDayStats(statsDate, agentId);
            // 从运营商日报表获取所分 换电金额数
            exchangePrice = exchangeMap != null && exchangeMap.get("money") != null ? Double.parseDouble(exchangeMap.get("money").toString()) / 100 : 0.0;

            totalOrderNumber = exchangeMap != null && exchangeMap.get("count") != null ? Integer.parseInt(exchangeMap.get("count").toString()) : 0 ;

            // new 权限设置（运营商和代理商可以查看故障电池）
            totalFaultBattery = batteryService.findFaults(sessionUser.getAgentId(), null);
            // new 权限设置（运营商和代理商可以查看异常电池）
            totalAbnormalBattery = batteryService.findAbnormal(sessionUser.getAgentId(), null);
        }

        // 定义集合接收查询运营商和代理商日报表信息
        Map<String, Object> exchange1 = null;
        Map<String, Object> exchange2 = null;
        // 定义变量接收查询的换电价格
        Double exPrice1=0.0;
        Double exPrice2=0.0;

        // 如果是 总部 登录
        if (sessionUser.getType() == User.Type.PLATFORM.getValue()) {
            exchange1 = reportService.findToDayStats(statsDate, agentId, agencyId);
            exchange2 = reportService.findAgentToDayStats(statsDate, agentId);
            // 获取钱并做空指针异常处理
            exPrice1 = exchange1 != null && exchange1.get("money") != null ? Double.parseDouble(exchange1 .get("money").toString()) / 100 : 0.0;
            exPrice2 = exchange2 != null && exchange2.get("money") != null ? Double.parseDouble(exchange2 .get("money").toString()) / 100 : 0.0;
            // 从运营商和代理商日报表中查询总换电金额
            //exchangePrice = Double.parseDouble(reportService.findAgentToDayStats(statsDate, agentId).get("money").toString())/ 100  +Double.parseDouble(reportService.findToDayStats(statsDate,agentId,agencyId).get("money").toString())/ 100;
            exchangePrice = exPrice1 + exPrice2;

            // 查询商品订单信息（订单数量、购买商品的金额）
            Map<String, Object> itemMap = itemOrderService.findToDayItemPrice(new Date());
            // 获取商品价格
            itemPrice = Double.valueOf(itemMap.get("totalPrice").toString()) / 100;
            itemtotal = Integer.valueOf(itemMap.get("total").toString());
            // 订单数量
            //totalOrderNumber1 = exchange1 != null && exchange1.get("count") != null ? Integer.parseInt(exchange1.get("count").toString()) : 0 ;
            // totalOrderNumber2 = exchange2 != null && exchange2.get("count") != null ? Integer.parseInt(exchange2.get("count").toString()) : 0 ;
            totalOrderNumber = exchange2 != null && exchange2.get("count") != null ? Integer.parseInt(exchange2.get("count").toString()) : 0+ itemtotal;

            totalFaultBattery = batteryService.findFault();
            // zxj 异常电池
            totalAbnormalBattery = batteryService.findAbnormal(null,null);

        }
        //Double exchangePrice = exchangeMap != null && exchangeMap.get("money") != null ? Double.parseDouble(exchangeMap.get("money").toString()) / 100 : 0.0;
        // 购买商品金额与 换电金额 （其中：非总部登录，商品金额收入为 0.0元）
        Double totalPrice = itemPrice + exchangePrice;

        // Integer totalOrderNumber = exchangeMap != null && exchangeMap.get("count") != null ? Integer.parseInt(exchangeMap.get("count").toString()) : 0 + itemtotal;
        String updateTime = exchangeMap != null && exchangeMap.get("updateTime") != null ? exchangeMap.get("updateTime").toString() : "";
        // 查询今日新增客户（日期：年月日）
        Integer totalNewPassport = passportService.findToDayTotal(new Date(), agentId, agencyId);
        model.addAttribute("flag", Stats.Flag.CABINET_DAY.getValue());
        model.addAttribute("statsDate", statsDate);
        model.addAttribute("updateTime", updateTime);
        model.addAttribute("totalPrice", totalPrice);
        model.addAttribute("totalFaultBattery", totalFaultBattery);
        model.addAttribute("totalAbnormalBattery", totalAbnormalBattery);
        model.addAttribute("totalNumber", totalOrderNumber);
        model.addAttribute("totalNewPassport", totalNewPassport);
        return "/security/main/index";
    }

    @ViewModel(ViewModel.INNER_PAGE)
    @RequestMapping(value = "password.htm", method = RequestMethod.GET)
    public void password() {
    }

    @ResponseBody
    @ViewModel(ViewModel.JSON)
    @RequestMapping(value = "password.htm", method = RequestMethod.POST)
    public ExtResult password(String oldPassword, String password, HttpSession session) {
        SessionUser sessionUser = getSessionUser(session);
        int effect = userService.updatePassword(sessionUser.getId(), CodecUtils.password(oldPassword), CodecUtils.password(password));
        if (effect == 0) {
            return ExtResult.failResult("原密码错误");
        } else {
            return ExtResult.successResult();
        }

    }

    @RequestMapping(value = "agent_tree.htm")
    public void agentTree(HttpSession httpSession, HttpServletResponse response) throws IOException {
        OutputStream stream = response.getOutputStream();
        stream.write(getSessionUser(httpSession).getAgentTree());
        stream.flush();
    }
    /**
    * 页面点击切换到其他用户时，显示不同状态
    * 
    * @Param: [agentId, agencyId, httpSession, response]
    * @Return: void
    * @Author By: zjn 2018/8/16  16:50
    */ 
    @RequestMapping(value = "agent.htm")
    public void agent(Integer agentId, Integer agencyId, HttpSession httpSession, HttpServletResponse response) {
        SessionUser sessionUser = getSessionUser(httpSession);

        if (agencyId != null) {
            sessionUser.setType(User.Type.AGENCY.getValue());
            sessionUser.switchAgency(agentId, agencyId);
            Agency agency = agencyService.find(agencyId);
            sessionUser.setTel(agency.getTel());
            sessionUser.setMemo(agency.getMemo());
            // 新增：总部切换到代理商页面时，更新代理商余额
            sessionUser.setBalance((double) agency.getBalance() / 100);
        } else if (agentId != null) {
            if (agentId == 0) {
                sessionUser.setType(User.Type.PLATFORM.getValue());
                // 加上下面2句，否则从运营商或者代理商切换回来后总部账户余额更新不回来
                Platform platform = platformService.find();
                sessionUser.setBalance((double)platform.getBalance()/100);
            } else {

                sessionUser.setType(User.Type.AGENT.getValue());
                Agent agent = agentService.find(agentId);
                sessionUser.setTel(agent.getTel());
                sessionUser.setMemo(agent.getMemo());
                // 新增：总部切换到运营商页面时，更新运营商余额
                sessionUser.setBalance((double) agent.getBalance() / 100);
        }
            sessionUser.switchAgent(agentId);
        }
//        if (user.getRoleId() != null) {
//            Role role = roleService.find(user.getRoleId());
//            sessionUser.setRoleName(role.getRoleName());
//            sessionUser.setOperCodeSet(roleService.loadOperCode(user.getRoleId()));
//        }
        response.setStatus(302);
        response.setHeader("Location", appConfig.contextPath + "/security/main/index.htm");
    }

    /**
     * 新增：总部余额弹窗显示
     *
     * @Param: [model, httpSession]
     * @Return: java.lang.String
     * @Author By: zjn 2018/9/3  9:55
     */
    @RequestMapping("viewPlatformMoney.htm")
    public String viewPlatformMoney(Model model) {

        Double sumPlatformMoney1=0.0;
        Double sumPlatformMoney2=0.0;
        // 查询运营商流水表中的按次换电总收入
        List<PlatformInOutMoney> platformInOutMoneyHuan =platformInOutMoneyService.find(PlatformInOutMoney.BizType.CHARGE_INCOME.getValue());
        if(platformInOutMoneyHuan == null){
            return SEGMENT_RECORD_NOT_FOUND;
        }
        // 遍历总收入
        for(PlatformInOutMoney huan : platformInOutMoneyHuan){
            // 转成double型
            Double money1 = huan.getMoney()!=null?Double.parseDouble(huan.getMoney().toString()):0.0;
            // 累计求和
            sumPlatformMoney1+=money1;
        }
        model.addAttribute("sumPlatformMoney1",sumPlatformMoney1);
        // 查询运营商流水表中的套餐总收入
        List<PlatformInOutMoney> platformInOutMoneyTaoCan = platformInOutMoneyService.find(PlatformInOutMoney.BizType.PACKET_INCOME.getValue());
        if (platformInOutMoneyTaoCan == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        }
        for(PlatformInOutMoney taocan : platformInOutMoneyTaoCan){
            Double money2 = taocan.getMoney()!=null?Double.parseDouble(taocan.getMoney().toString()):0.0;
            // 套餐求和
            sumPlatformMoney2+=money2;
        }
        model.addAttribute("sumPlatformMoney2",sumPlatformMoney2);
        // 查询总部信息
        Platform entity = platformService.find();
        //总收入
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        return "/security/main/viewPlatformMoney";
    }
    /**
    * 新增：运营商余额弹窗显示
    * 
    * @Param: [model, httpSession]
    * @Return: java.lang.String
    * @Author By: zjn 2018/9/3  9:55
    */ 
    @RequestMapping("viewAgentMoney.htm")
    public String viewAgentMoney(Model model,HttpSession httpSession) {
        SessionUser sessionUser = getSessionUser(httpSession);
        Integer id = sessionUser.getAgentId();
        Agent entity = agentService.find(id);

        Double sumAgentMoney1=0.0;
        Double sumAgentMoney2=0.0;
        // 查询运营商流水表中的按次换电总收入
        List<AgentInOutMoney> agentInOutMoneyHuan =agentInOutMoneyService.find(entity.getId(),AgentInOutMoney.BizType.CHARGE_INCOME.getValue());
        if(agentInOutMoneyHuan == null){
            return SEGMENT_RECORD_NOT_FOUND;
        }
        // 遍历总收入
        for(AgentInOutMoney huan : agentInOutMoneyHuan){
            // 转成double型
            Double money1 = huan.getMoney()!=null?Double.parseDouble(huan.getMoney().toString()):0.0;
            // 累计求和
            sumAgentMoney1+=money1;
        }
        model.addAttribute("sumAgentMoney1",sumAgentMoney1);
        // 查询运营商流水表中的套餐总收入
        List<AgentInOutMoney> agentInOutMoneyTaoCan = agentInOutMoneyService.find(entity.getId(),AgentInOutMoney.BizType.PACKET_INCOME.getValue());
        if (agentInOutMoneyTaoCan == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        }
        for(AgentInOutMoney taocan : agentInOutMoneyTaoCan){
            Double money2 = taocan.getMoney()!=null?Double.parseDouble(taocan.getMoney().toString()):0.0;
            // 套餐求和
            sumAgentMoney2+=money2;
        }
        model.addAttribute("sumAgentMoney2",sumAgentMoney2);

        //总收入
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        return "/security/main/viewAgentMoney";
    }
    /**
    * 新增：代理商余额弹窗显示
    *
    * @Param: [model, httpSession]
    * @Return: java.lang.String
    * @Author By: zjn 2018/9/3  15:43
    */
    @RequestMapping(value = "viewAgencyMoney.htm")
    public String viewAgencyMoney(Model model, HttpSession httpSession) {
        SessionUser sessionUser = getSessionUser(httpSession);
        Integer id = sessionUser.getAgencyId();
        Double sumAgencyMoney1=0.0;
        Double sumAgencyMoney2=0.0;
        // 查询代理商流水表中的按次换电总收入
        List<AgencyInOutMoney> agencyInOutMoneyHuan =agencyInOutMoneyService.find(id,AgencyInOutMoney.BizType.CHARGE_INCOME.getValue());
        if (agencyInOutMoneyHuan == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        }
        // 遍历总收入
        for(AgencyInOutMoney huan : agencyInOutMoneyHuan){
            // 转成double型
            Double money1 = huan.getMoney()!=null?Double.parseDouble(huan.getMoney().toString()):0.0;
            // 累计求和
            sumAgencyMoney1+=money1;
        }
        model.addAttribute("sumAgencyMoney1",sumAgencyMoney1);
        // 查询代理商流水表中的套餐总收入
        List<AgencyInOutMoney> agencyInOutMoneyTaoCan = agencyInOutMoneyService.find(id,AgencyInOutMoney.BizType.PACKET_INCOME.getValue());
        if (agencyInOutMoneyTaoCan == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        }
        for(AgencyInOutMoney taocan : agencyInOutMoneyTaoCan){
            Double money2 = taocan.getMoney()!=null?Double.parseDouble(taocan.getMoney().toString()):0.0;
            // 套餐求和
            sumAgencyMoney2+=money2;
        }
        model.addAttribute("sumAgencyMoney2",sumAgencyMoney2);

        Agency entity = agencyService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        return "/security/main/viewAgencyMoney";
    }

    @RequestMapping(value = "module.htm")
    public void agent(String url, HttpServletResponse response) {
        response.setStatus(302);
        response.setHeader("Location", url);
    }

    @RequestMapping(value = "portrait.htm", method = RequestMethod.GET)
    public void portrait() {
    }

    @RequestMapping(value = "portrait.htm", method = RequestMethod.POST)
    public String portrait(@RequestParam("file") MultipartFile file, Model model) throws IOException {
        File sourceFile = new File(getAppConfig().tempDir, IdUtils.uuid() + "." + YhdwUtils.getFileSuffix(file.getOriginalFilename()));
        YhdwUtils.makeParentDir(sourceFile);
        file.transferTo(sourceFile);
        model.addAttribute("filePath", AppConstant.PATH_TEMP + sourceFile.getName());
        model.addAttribute("fileName", file.getOriginalFilename());

        return "/security/main/portrait_response";
    }
}
